package com.boot.core.task

import com.boot.core.util.ActivemqManager
import com.boot.core.result.MsgBean
import com.boot.mgt.dao.mysql.TaAccidentMapper
import com.boot.mgt.dao.mysql.TaAccidentReportAssignMapper
import com.boot.mgt.dao.mysql.TaAccidentReportMapper
import com.boot.mgt.dao.mysql.TaAcdFile2018Mapper
import com.boot.mgt.model.TaAccident
import com.boot.mgt.model.TaAccidentReportAssign
import com.boot.mgt.model.TaAcdFile2018
import com.boot.mgt.model.vo.TaPoliceSituationMonitoringVo
import com.boot.mgt.service.TaAccidentService
import com.boot.mgt.service.TaAcdFile2018Service
import com.boot.mgt.service.TaPoliceSituationMonitoringService
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import tk.mybatis.mapper.entity.Example
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.*


@Component
class ObjectTask {

    @Autowired
    private lateinit var accidentReportAssignMapper: TaAccidentReportAssignMapper

    @Autowired
    private lateinit var accidentReportMapper: TaAccidentReportMapper

    @Autowired
    private lateinit var activemqManager: ActivemqManager

    @Autowired
    private lateinit var taAccidentService: TaAccidentService

    @Autowired
    private lateinit var taAccidentMapper: TaAccidentMapper

    @Autowired
    private lateinit var taAcdFile2018Mapper: TaAcdFile2018Mapper

    @Autowired
    private lateinit var taAcdFile2018Service: TaAcdFile2018Service

    @Autowired
    private lateinit var taPoliceSituationMonitoringService: TaPoliceSituationMonitoringService

    /**
     * 定时推送
     */
//    @Scheduled(cron = "0 0/1 * * * ?")
    fun sendPush() {
        log.debug("推送定时任务开始")
        TaAccidentReportAssign().apply {
            hasAccepted = 2
            val accidentReportAssign = accidentReportAssignMapper.select(this)
            for (taAccidentReportAssign in accidentReportAssign) {
                if (isDiffer3Min(taAccidentReportAssign.addTime?.time ?: Date().time)) {
                    taAccidentReportAssign.assignedPoliceNumber?.let {
                        val accidentReport = accidentReportMapper
                                .selectByPrimaryKey(taAccidentReportAssign.accidentReportId)
                        MsgBean().apply {
                            policeNumber = assignedPoliceNumber
                            put("address", accidentReport.address!!)
                            put("taAccidentReportId", accidentReport.id!!)
                            activemqManager.send(this)
                        }
                    }
                }
            }
        }
        log.debug("推送定时任务结束")
    }

    /**
     * 定时获取位置信息
     */
    //modified by liuzhe @2019-03-14 ：调整sql语句，只筛选需要获取道路信息的记录
//    @Suppress("NAME_SHADOWING")
//    @Scheduled(cron = "0 */15 * * * ?")
    fun selectPosition() {
        log.info("开始执时获取位置信息数据定时任务")
        val example = Example(TaAccident::class.java)
        val unPositionCriteria = example.createCriteria()
        unPositionCriteria.andEqualTo("state", 3)
        unPositionCriteria.andIsNull("locationIdList")
        unPositionCriteria.andIsNotNull("amapLatitude")
        unPositionCriteria.andIsNotNull("amapLongitude")
        val targetAccident = taAccidentMapper.selectByExample(example)
        for (taAccident in targetAccident) {
            taAccidentService.selectPosition(taAccident, true)
        }
        log.info("开始执时获取2018位置信息数据定时任务")
        val example2 = Example(TaAcdFile2018::class.java)
        example2.createCriteria()
                .andIsNotNull("latitude").andIsNotNull("longitude")
                .andIsNull("locationIdList").andIsNull("geojsonList")
        val taAcdFile2018 = taAcdFile2018Mapper.selectByExample(example2)
        for (taAcdFile2018 in taAcdFile2018) {
            taAcdFile2018Service.selectPosition(taAcdFile2018)
        }
    }

    /**
     * 定时任务- 警情监控
     * 暂时是定每30分钟统计执行一次: cron = "0 10 * * * ?"
     */
//    @Scheduled(fixedRate = 1000 * 5)
//    @Scheduled(cron = "0 30 * * * ?")
    fun policeSituationMonitoring() {
        log.info("policeSituationMonitoring execute start: {}", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
        var taPoliceSituationMonitoringOvertimeResultList = taPoliceSituationMonitoringService.searchOvertimeResultList(mapOf());
        if(taPoliceSituationMonitoringOvertimeResultList!=null && taPoliceSituationMonitoringOvertimeResultList.size>0) {
            taPoliceSituationMonitoringOvertimeResultList.forEach() {
                var regionId = it?.regionId
                var dateNow = DateTimeFormatter.ofPattern("yyyyMMdd").format(LocalDate.now())
//                var dateNow = it.timeTag
                var taPoliceSituationMonitoringVo = taPoliceSituationMonitoringService.detail(null, dateNow, regionId)
                if(taPoliceSituationMonitoringVo!=null) {
                    // 超时未接警数量
//                    taPoliceSituationMonitoringVo.casesAcceptedOvertime = taPoliceSituationMonitoringVo.casesAcceptedOvertime?.plus(1)
                    // 方案一
//                    taPoliceSituationMonitoringVo.casesAcceptedCalledOvertime = it.casesAcceptedCalledOvertime?.plus(1)
//                    taPoliceSituationMonitoringVo.casesAcceptedActionOvertime = it.casesAcceptedActionOvertime?.plus(1)
                    // 方案2
                    taPoliceSituationMonitoringVo.casesAcceptedCalledOvertime = it?.casesAcceptedCalledOvertime
                    taPoliceSituationMonitoringVo.casesAcceptedActionOvertime = it?.casesAcceptedActionOvertime
                    // 超时未处理数量 暂时不处理
//                    taPoliceSituationMonitoringVo.dealOvertime = it.dealOvertime
                    // 超时未上报数量 暂时不处理
//                    taPoliceSituationMonitoringVo.casesReportOvertime = it.casesReportOvertime
                    // 超期未结案数量
//                    taPoliceSituationMonitoringVo.casesOpenedOvertime = taPoliceSituationMonitoringVo.casesOpenedOvertime?.plus(1)
//                    taPoliceSituationMonitoringVo.casesOpenedOvertime = it.casesOpenedOvertime?.plus(1)
                    taPoliceSituationMonitoringVo.casesOpenedOvertime = it?.casesOpenedOvertime
                    taPoliceSituationMonitoringService.update(taPoliceSituationMonitoringVo)
                } else {
                    it?.timeTag = dateNow
                    if (it != null) {
                        taPoliceSituationMonitoringService.insert(it)
                    }
                }
            }
        }
        log.info("policeSituationMonitoring execute start: {}", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
    }

    companion object {
        private val log: Logger = LoggerFactory.getLogger(this::class.java)

        fun isDiffer3Min(time: Long): Boolean {
            val start = process(time)
            val end = process(Date().time)
            return end - start != 0L && (end - start) % (3 * 60) == 0L
        }

        private fun process(timestamp: Long): Long {
            val calendar = Calendar.getInstance()
            calendar.timeInMillis = timestamp
            calendar.set(Calendar.SECOND, 0)
            return calendar.timeInMillis / 1000
        }
    }

}